import type { ComputedRef, Ref } from "vue";
import type { DictItemListResult } from "@/api/types";
import type { UseBaseTable } from "@/composables";
import { ElMessage } from "element-plus";
import { computed, reactive } from "vue";
import { dictItemApi } from "@/api";
import { useBaseTable } from "@/composables";
import { $t } from "@/plugins/i18n";
import { apiCall } from "@/utils/http/apiCall";

interface UseDictItemTable extends Omit<UseBaseTable<DictItemListResult>, "tablePage" | "tableData"> {
    /** 查询表单 */
    tableQuery: { name: string | null };
    /** 过滤后的数据 */
    tableFilteredData: ComputedRef<DictItemListResult[]>;
    /** 获取表格数据 */
    fetchTableData: () => void;
    /** 设置为默认值 */
    handleSetDefault: (id: string) => void;
    /** 取消默认值 */
    handleCancelDefault: (id: string) => void;
    /** 删除字典项 */
    handleDelete: (id: string) => void;
}

export function useDictItemTable(typeCode: Ref<string>): UseDictItemTable {
    const { tableLoading, tableData } = useBaseTable<DictItemListResult>();

    /** 查询表单 */
    const tableQuery = reactive<{ name: string | null }>({
        name: null,
    });

    /** 过滤后的数据 */
    const tableFilteredData = computed(() => {
        const name = tableQuery.name || "";
        if (!name.trim()) {
            return tableData.value;
        }
        return tableData.value.filter(item =>
            item.name.toLowerCase().includes(name.toLowerCase()),
        );
    });

    /** 获取表格数据 */
    function fetchTableData(): void {
        tableLoading.value = true;
        apiCall(
            () => dictItemApi.list(typeCode.value),
            (data) => {
                tableData.value = data;
            },
            {
                onFinally: () => {
                    tableLoading.value = false;
                },
            },
        );
    }

    /** 设置为默认值 */
    function handleSetDefault(id: string): void {
        apiCall(
            () => dictItemApi.updateDefault(id, typeCode.value),
            (data, resp) => {
                ElMessage.success($t(resp.message));
                fetchTableData();
            },
        );
    }

    /** 取消默认值 */
    function handleCancelDefault(id: string): void {
        apiCall(
            () => dictItemApi.cancelDefault(id),
            (data, resp) => {
                ElMessage.success($t(resp.message));
                fetchTableData();
            },
        );
    }

    /** 删除字典项 */
    function handleDelete(id: string): void {
        apiCall(
            () => dictItemApi.remove(id),
            (data, resp) => {
                ElMessage.success($t(resp.message));
                fetchTableData();
            },
        );
    }

    return {
        tableLoading,
        tableQuery,
        tableFilteredData,
        fetchTableData,
        handleSetDefault,
        handleCancelDefault,
        handleDelete,
    };
}
